﻿Imports System.ComponentModel
Imports WRDB.DBProviders

Public Class frmImportScheduled

    Private lstImports As New Generic.List(Of clsImport)

    Private Sub frmArchiveScheduled_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        Try

            With cboDatabaseType
                .Items.Clear()
                For dbType As clsDB.enumDBType = clsDB.enumDBType.Paradox To clsDB.enumDBType.SQLite
                    Select Case dbType
                        Case clsDB.enumDBType.Firebird, clsDB.enumDBType.MySQL, clsDB.enumDBType.Oracle, clsDB.enumDBType.SQL_Server
                            Dim dbTypeName As String = dbType.ToString.Replace("_", " ")
                            .Items.Add(dbTypeName)
                    End Select
                Next
            End With
            cboDatabaseType.SelectedIndex = -1

            tblFile.Visible = False
            tblSCADA.Visible = False
            tblAquarius.Visible = False

            'load saved connections
            Dim NumConnections As Integer = GetKey(enumTaskKey.NumConnections, 0)
            lstImports.Clear()
            cboConnectionName.Items.Clear()
            For i As Integer = 0 To NumConnections - 1
                Dim SectionName As String = "Connection_" & i
                Dim Import As clsImport = clsImport.GetImport(SectionName)
                If Import IsNot Nothing Then
                    Import.Load(SectionName)
                    lstImports.Add(Import)
                    cboConnectionName.Items.Add(Import.ConnectionName)
                End If
            Next

            chkActivate.Checked = GetKey(enumTaskKey.ImportActivated, False)

            cboProjectDest.Items.Clear()
            cboProjectDest.Items.AddRange(clsConnections.GetProjectList.Keys.ToArray)
            cboDatabaseType.Items.AddRange([Enum].GetNames(GetType(clsDB.enumDBType)))

            cboConnectionName.Text = GetKey(enumTaskKey.LastConnection, "")
            If cboConnectionName.SelectedIndex = -1 And lstImports.Count > 0 Then cboConnectionName.SelectedIndex = 0

            txtTime.Text = GetKey(enumTaskKey.ImportTime, "03:00")

            lblProgress.Text = ""
            ImportForm = Me

        Catch ex As Exception

            ErrorMsg(, ex)

        End Try

    End Sub

    Private Sub cboConnectionName_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboConnectionName.SelectedIndexChanged
        FillConnection()
    End Sub

    Private Sub FillConnection()
        Try
            Me.SuspendLayout()

            Dim Import As clsImport = lstImports(cboConnectionName.SelectedIndex)
            With Import
                If cboConnectionName.SelectedIndex = -1 Then
                    lblProjectDest.Enabled = False
                    cboProjectDest.Enabled = False
                    lblTableDest.Enabled = False
                    cboTableDest.Enabled = False
                    cboProjectDest.Items.Clear()
                    cboTableDest.Items.Clear()
                    txtMinDays.Text = ""
                    txtMaxDays.Text = ""
                    chkActiveConnection.Checked = False
                    chkDateRange.Checked = False
                Else
                    lblProjectDest.Enabled = True
                    cboProjectDest.Enabled = True
                    lblTableDest.Enabled = True
                    cboTableDest.Enabled = True

                    tblFile.Visible = .ConnectionType = clsImport.enumConnectionType.File
                    tblSCADA.Visible = .ConnectionType = clsImport.enumConnectionType.SCADA
                    tblAquarius.Visible = .ConnectionType = clsImport.enumConnectionType.Aquarius
                    tblHydrolynx.Visible = .ConnectionType = clsImport.enumConnectionType.Hydrolynx

                    txtMinDays.Enabled = (.ConnectionType <> clsImport.enumConnectionType.File)

                    cboProjectDest.Text = .WRDBProjectName
                    cboTableDest.Text = .WRDBTable
                    txtMinDays.Text = .MinDays
                    txtMaxDays.Text = .MaxDays
                    chkActiveConnection.Checked = .Activated
                    chkDateRange.Checked = .OverrideDateRange And .ConnectionType <> clsImport.enumConnectionType.File
                    dtFirstDate.Value = .FirstDate
                    dtLastDate.Value = .LastDate

                    Select Case .ConnectionType
                        Case clsImport.enumConnectionType.File
                            With CType(Import, clsImportFile)
                                txtFolder.Text = .ImportFolder
                                txtHeader.Text = .MappingFile
                            End With
                        Case clsImport.enumConnectionType.SCADA
                            With CType(Import, clsImportSCADA)
                                cboDatabaseType.Text = .DatabaseType.ToString.Replace("_", " ")
                                txtServerSCADA.Text = .ServerName
                                txtDatabaseName.Text = .DatabaseName
                                chkWindowsSecurity.Checked = .UserName = ""
                                txtUserNameSCADA.Text = .UserName
                                txtPswdSCADA.Text = .Password
                                cboTableSCADA.Text = .SourceTable
                                txtMappingSCADA.Text = .MappingFile
                            End With
                        Case clsImport.enumConnectionType.Aquarius
                            With CType(Import, clsImportAquarius)
                                cboAPI.SelectedIndex = .APIVer
                                txtServerAquarius.Text = .ServerName
                                txtUserNameAquarius.Text = .UserName
                                txtPswdAquarius.Text = .Password
                                txtMappingAquarius.Text = .MappingFile
                                chkResampleAquarius.Checked = .Resample
                                txtResampleAquarius.Text = .ResampleInterval
                            End With
                        Case clsImport.enumConnectionType.Hydrolynx
                            With CType(Import, clsImportHydrolynx)
                                txtFolderHydrolynx.Text = .ImportFolder
                                txtMappingHydrolynx.Text = .MappingFile
                                chkResampleHydrolynx.Checked = .Resample
                                Select Case .ResampleInterval
                                    Case 15
                                        cboResampleHydrolynx.SelectedIndex = 0
                                    Case 30
                                        cboResampleHydrolynx.SelectedIndex = 1
                                    Case 60
                                        cboResampleHydrolynx.SelectedIndex = 2
                                    Case Else
                                        cboResampleHydrolynx.SelectedIndex = -1
                                End Select
                            End With

                    End Select
                End If
            End With
        Catch ex As Exception
            ErrorMsg(, ex)
        Finally
            Me.ResumeLayout()
        End Try
    End Sub

    Private Sub btnNew_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNew.Click
        Try
            With New frmNewImport
                .cboType.SelectedIndex = 0
                If .ShowDialog = DialogResult.OK Then
                    If cboConnectionName.Items.Contains(.txtName.Text) Then
                        WarningMsg("This connection name already exists; you must create unique names.")
                        Exit Sub
                    End If
                    Dim NewName As String = .txtName.Text
                    Dim NewType As clsImport.enumConnectionType = .cboType.SelectedIndex
                    Select Case NewType
                        Case clsImport.enumConnectionType.File : lstImports.Add(New clsImportFile(NewName))
                        Case clsImport.enumConnectionType.SCADA : lstImports.Add(New clsImportSCADA(NewName))
                        Case clsImport.enumConnectionType.Aquarius : lstImports.Add(New clsImportAquarius(NewName))
                        Case clsImport.enumConnectionType.Hydrolynx : lstImports.Add(New clsImportHydrolynx(NewName))
                    End Select
                    cboConnectionName.Items.Add(NewName)
                    cboConnectionName.Text = NewName
                    cboDatabaseType.SelectedIndex = -1
                End If
            End With
        Catch ex As Exception
            ErrorMsg(, ex)
        End Try
    End Sub

    Private Sub btnDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDelete.Click
        Try
            If cboConnectionName.SelectedIndex <> -1 AndAlso
                       WarningMsg("Are you sure you want to delete all information for this connection?") = Windows.Forms.DialogResult.OK Then
                lstImports.RemoveAt(cboConnectionName.SelectedIndex)
                cboConnectionName.Items.Remove(cboConnectionName.Text)

                'clear out form in case there are no other configurations left to refresh with
                cboDatabaseType.SelectedIndex = -1

                cboConnectionName.SelectedIndex = IIf(cboConnectionName.Items.Count = 0, -1, 0)
            End If
        Catch ex As Exception
            ErrorMsg(, ex)
        End Try
    End Sub

    Private Sub cboProjectDest_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboProjectDest.SelectedIndexChanged
        Try

            lstImports(cboConnectionName.SelectedIndex).WRDBProjectName = cboProjectDest.Text
            cboTableDest.Items.Clear()
            If cboProjectDest.SelectedIndex <> -1 Then
                Try
                    Dim Project As New clsProject(cboProjectDest.Text)
                    If Not Project.DB.TestConnectionQuick(5) Then
                        WarningMsg("Unable to connect to this WRDB project.")
                        Exit Sub
                    End If
                    For Each s In Project.GetTableList(clsProject.enumTableTypes.Working, clsProject.enumTableTypes.Master)
                        cboTableDest.Items.Add(s)
                    Next
                    cboTableDest.Text = lstImports(cboConnectionName.SelectedIndex).WRDBTable
                    If cboTableDest.SelectedIndex = -1 AndAlso cboTableDest.Items.Count > 0 Then cboTableDest.SelectedIndex = 0
                Catch ex As Exception
                End Try
            End If

        Catch ex As Exception

            ErrorMsg(, ex)

        End Try
    End Sub

    Private Sub cboTableDest_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboTableDest.SelectedIndexChanged
        lstImports(cboConnectionName.SelectedIndex).WRDBTable = cboTableDest.Text
    End Sub

    Private Sub btnTest_Click(sender As Object, e As EventArgs) Handles btnTest.Click
        Try
            If cboConnectionName.SelectedIndex = -1 Then Exit Sub
            If TestConnection() Then
                MessageBox.Show("Successfully connected to database.", "Test Connection", MessageBoxButtons.OK, MessageBoxIcon.Information)
            Else
                MessageBox.Show("Unable to connect to database.", "Test Connection", MessageBoxButtons.OK, MessageBoxIcon.Error)
            End If
        Catch ex As Exception
            ErrorMsg(, ex)
        End Try
    End Sub

    Private Function TestConnection() As Boolean
        Try
            If txtServerSCADA.Text.Trim = "" Or txtDatabaseName.Text.Trim = "" Or cboDatabaseType.SelectedIndex = -1 Then
                WarningMsg("You must specify the database type, server name, and database name.")
                Return False
            End If
            Dim DataSource As String = txtServerSCADA.Text
            Dim DatabaseName As String = txtDatabaseName.Text
            Dim DBType As WRDB.DBProviders.clsDB.enumDBType = [Enum].Parse(GetType(clsDB.enumDBType), cboDatabaseType.Text.Replace(" ", "_"))
            Dim DB As WRDB.DBProviders.clsDB = Nothing

            Select Case cboDatabaseType.SelectedIndex
                Case clsDB.enumDBType.Firebird
                    'database files will be stored on server in the root directory, and given the extension fdb
                    DatabaseName = String.Format("\{0}.fdb", DatabaseName)
            End Select

            Try
                DB = clsDB.GetDataProvider(DBType, DataSource, DatabaseName, txtUserNameSCADA.Text, txtPswdSCADA.Text, 60)
                If DB Is Nothing Then Return False
            Catch ex As DbSqlException
                ErrorMsg("Unable to connect to database.", ex)
                Return False
            Catch ex As Exception
                Return False
            End Try

            'make sure database exists & offer to create

            Dim port As Integer = 0
            Dim moreinfo As String = ""
            Select Case DBType
                Case clsDB.enumDBType.Firebird : port = 3050 : moreinfo = " The .fdb database file MUST be stored in the root directory of the server."
                Case clsDB.enumDBType.MySQL : port = 3306
                Case clsDB.enumDBType.Oracle : port = 1521  'moreinfo = " The owner of all tables MUST be designated as 'WRDB'."
                Case clsDB.enumDBType.SQL_Server : port = 1433
            End Select
            Dim info As String = String.Format("Note: this provider communicates with the database server using TCP/IP port number {0} by default. You may have to configure your computer (and workgroup's) firewall to allow traffic through this port.{1}", port, moreinfo)

            If Not DB.TestConnectionQuick(5) Then
                'MainForm.ProgressComplete()

                Select Case DB.DatabaseType
                    Case clsDB.enumDBType.SQL_Server, clsDB.enumDBType.MySQL
                        DB = clsDB.GetDataProvider(DBType, DataSource, IIf(DB.DatabaseType = clsDB.enumDBType.SQL_Server, "master", "mysql"), txtUserNameSCADA.Text, txtPswdSCADA.Text, 10)
                        If DB Is Nothing Then Return False
                        If Not DB.OpenConnection() Then
                            WarningMsg("Unable to connect to specified data provider database. Please check all connection and security settings." & vbCr & vbCr & info & vbCr & vbCr & DB.LastException.Message & vbCr & vbCr & DB.LastException.InnerException.Message)
                            Return False
                        End If
                        Dim dt As DataTable = DB.Connection.GetSchema("DATABASES")

                        Dim found As Boolean = False
                        For Each dr As DataRow In dt.Rows
                            If dr("Database_Name").ToString.Equals(DatabaseName, StringComparison.OrdinalIgnoreCase) Then found = True : Exit For
                        Next
                        dt.Dispose()
                        dt = Nothing

                        If Not found Then
                            WarningMsg("The selected database was not found. Please contact your database administrator for assistance.")
                            Return False
                        End If

                    Case clsDB.enumDBType.Oracle
                        If DB.Connection Is Nothing Then Return False 'do not allow user to create database (actually schema) because they are mapped to username by DBA
                        If Not DB.OpenConnection() Then
                            WarningMsg("Unable to connect to specified data provider database. Please check all connection and security settings." & vbCr & info & vbCr & vbCr & DB.LastException.Message)
                            Return False
                        End If

                    Case clsDB.enumDBType.Firebird
                        'GetSchema doesn't include any way to list databases on Firebird server; just try to connect and if error, offer to create
                        'note that dbname in Firebird is actually full path to the database file on the server; place all on root directory under WRDB
                        If Not DB.OpenConnection() Then
                            WarningMsg(StringFormat("Either the Firebird server couldn't be accessed or the database '{0}' was not found. Please check all connection and security settings.\n{1}", IO.Path.GetFileNameWithoutExtension(DB.DatabaseName), info))
                            Return False
                        End If
                End Select
            End If

            With cboTableSCADA
                .AutoCompleteMode = AutoCompleteMode.None
                .AutoCompleteSource = AutoCompleteSource.None
                .Items.Clear()
                .Items.AddRange(DB.GetTableList.ToArray)
                'following must be set when dropdown closes
                '.AutoCompleteMode = AutoCompleteMode.SuggestAppend
                '.AutoCompleteSource = AutoCompleteSource.ListItems
            End With

            DB.Connection.Close()
            Return True

        Catch ex As DbSqlException
            WarningMsg(ex.Message)
            Return False
        Catch ex As Exception
            ErrorMsg(, ex)
            Return False
        Finally
            'WriteProgress()
        End Try
    End Function

    Private Sub btnFolder_Click(sender As System.Object, e As System.EventArgs) Handles btnFolder.Click
        Try

            With New FolderBrowserDialog
                .ShowNewFolderButton = True
                .SelectedPath = txtFolder.Text
                If .ShowDialog(Me) = Windows.Forms.DialogResult.OK Then
                    txtFolder.Text = .SelectedPath
                    CType(lstImports(cboConnectionName.SelectedIndex), clsImportFile).ImportFolder = .SelectedPath
                End If
            End With

        Catch ex As Exception

            ErrorMsg(, ex)

        End Try
    End Sub

    Private Sub btnHeader_Click(sender As System.Object, e As System.EventArgs) Handles btnHeader.Click
        Try

            With New OpenFileDialog
                .FileName = txtHeader.Text
                .Filter = "Header files|*.hdr"
                .Multiselect = False
                .InitialDirectory = MyDataPath()
                If .ShowDialog(Me) = Windows.Forms.DialogResult.OK Then
                    txtHeader.Text = .FileName
                    lstImports(cboConnectionName.SelectedIndex).MappingFile = .FileName
                End If
            End With

        Catch ex As Exception

            ErrorMsg(, ex)

        End Try
    End Sub

    Private Sub btnFolderHydrolynx_Click(sender As System.Object, e As System.EventArgs) Handles btnFolderHydrolynx.Click
        Try

            With New FolderBrowserDialog
                .ShowNewFolderButton = True
                .SelectedPath = txtFolder.Text
                If .ShowDialog(Me) = Windows.Forms.DialogResult.OK Then
                    txtFolderHydrolynx.Text = .SelectedPath
                    CType(lstImports(cboConnectionName.SelectedIndex), clsImportHydrolynx).ImportFolder = .SelectedPath
                End If
            End With

        Catch ex As Exception

            ErrorMsg(, ex)

        End Try
    End Sub

    Private Sub btnMappingHydrolynx_Click(sender As Object, e As EventArgs) Handles btnMappingHydrolynx.Click
        Try

            With New OpenFileDialog
                .FileName = txtMappingHydrolynx.Text
                .Filter = "Hydrolynx Mapping files|*.txt"
                .Multiselect = False
                .InitialDirectory = MyDataPath()
                If .ShowDialog(Me) = Windows.Forms.DialogResult.OK Then
                    txtMappingHydrolynx.Text = .FileName
                    lstImports(cboConnectionName.SelectedIndex).MappingFile = txtMappingHydrolynx.Text
                End If
            End With

        Catch ex As Exception

            ErrorMsg(, ex)

        End Try
    End Sub

    Private Sub btnMappingAquarius_Click(sender As Object, e As EventArgs) Handles btnMappingAquarius.Click
        Try

            With New OpenFileDialog
                .FileName = txtMappingAquarius.Text
                .Filter = "Aquarius Mapping files|*.txt"
                .Multiselect = False
                .InitialDirectory = MyDataPath()
                If .ShowDialog(Me) = Windows.Forms.DialogResult.OK Then
                    txtMappingAquarius.Text = .FileName
                    lstImports(cboConnectionName.SelectedIndex).MappingFile = txtMappingAquarius.Text
                End If
            End With

        Catch ex As Exception

            ErrorMsg(, ex)

        End Try
    End Sub

    Private Sub btnMappingSCADA_Click(sender As Object, e As EventArgs) Handles btnMappingSCADA.Click
        Try

            With New OpenFileDialog
                .FileName = txtMappingSCADA.Text
                .Filter = "SCADA Mapping files|*.txt"
                .Multiselect = False
                .InitialDirectory = MyDataPath()
                If .ShowDialog(Me) = Windows.Forms.DialogResult.OK Then
                    txtMappingSCADA.Text = .FileName
                    lstImports(cboConnectionName.SelectedIndex).MappingFile = txtMappingSCADA.Text
                End If
            End With

        Catch ex As Exception

            ErrorMsg(, ex)

        End Try

    End Sub

    Private Sub btnBuild_Click(sender As Object, e As EventArgs) Handles btnBuild.Click
        With lstImports(cboConnectionName.SelectedIndex)
            .BuildMapping(.MappingFile)
        End With
    End Sub

    Private Sub btnBuildHydrolynx_Click(sender As Object, e As EventArgs) Handles btnBuildHydrolynx.Click
        With lstImports(cboConnectionName.SelectedIndex)
            .BuildMapping(.MappingFile)
            txtMappingHydrolynx.Text = .MappingFile
        End With
    End Sub

    Private Sub btnBuildAquarius_Click(sender As Object, e As EventArgs) Handles btnBuildAquarius.Click
        With lstImports(cboConnectionName.SelectedIndex)
            .BuildMapping(.MappingFile)
            txtMappingAquarius.Text = .MappingFile
        End With
    End Sub

    Private Sub btnBuildSCADA_Click(sender As Object, e As EventArgs) Handles btnBuildSCADA.Click
        With lstImports(cboConnectionName.SelectedIndex)
            .BuildMapping(.MappingFile)
            txtMappingSCADA.Text = .MappingFile
        End With
    End Sub

    Private Sub cboDatabaseType_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboDatabaseType.SelectedIndexChanged
        Try
            If cboDatabaseType.SelectedIndex = -1 Then Exit Sub
            Dim DbType As clsDB.enumDBType = [Enum].Parse(GetType(clsDB.enumDBType), cboDatabaseType.Text.Replace(" ", "_"))
            CType(lstImports(cboConnectionName.SelectedIndex), clsImportSCADA).DatabaseType = DbType

            'all the following may have been made invisible if creating a new project and no database type selected yet
            lblServerSCADA.Visible = True
            txtServerSCADA.Visible = True

            btnTest.Visible = True

            If DbType = clsDB.enumDBType.SQL_Server Then
                chkWindowsSecurity.Visible = True
                chkWindowsSecurity.Checked = True
            Else
                chkWindowsSecurity.Visible = False
                chkWindowsSecurity.Checked = False
            End If

            'note: Oracle employs tablespaces, rather than databases; these are mapped to a specific username
            'for now, do not allow tablespaces to be created by user (must be DBA)
        Catch ex As Exception
            ErrorMsg(, ex)
        End Try
    End Sub

    Private Sub cboResampleHydrolynx_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboResampleHydrolynx.SelectedIndexChanged
        CType(lstImports(cboConnectionName.SelectedIndex), clsImportHydrolynx).ResampleInterval = Val(cboResampleHydrolynx.Text)
    End Sub

    Private Sub cboTableSCADA_DropDown(sender As Object, e As EventArgs) Handles cboTableSCADA.DropDown
        TestConnection()
    End Sub

    Private Sub cboAPI_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboAPI.SelectedIndexChanged
        CType(lstImports(cboConnectionName.SelectedIndex), clsImportAquarius).APIVer = cboAPI.SelectedIndex
        chkResampleAquarius.Enabled = cboAPI.SelectedIndex = 0
        txtResampleAquarius.Enabled = cboAPI.SelectedIndex = 0
    End Sub

    Private Sub chkActiveConnection_CheckedChanged(sender As Object, e As EventArgs) Handles chkActiveConnection.CheckedChanged
        lstImports(cboConnectionName.SelectedIndex).Activated = chkActiveConnection.Checked
    End Sub

    Private Sub chkActivate_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles chkActivate.CheckedChanged
        Dim tf As Boolean = chkActivate.Checked
        lblTime.Enabled = tf
        txtTime.Enabled = tf
    End Sub

    Private Sub chkWindowsSecurity_CheckedChanged(sender As Object, e As EventArgs) Handles chkWindowsSecurity.CheckedChanged
        Dim tf As Boolean = Not chkWindowsSecurity.Checked
        lblUserNameSCADA.Visible = tf
        txtUserNameSCADA.Visible = tf
        txtPswdSCADA.Visible = tf
    End Sub

    Private Sub chkResampleHydrolynx_CheckedChanged(sender As Object, e As EventArgs) Handles chkResampleHydrolynx.CheckedChanged
        CType(lstImports(cboConnectionName.SelectedIndex), clsImportHydrolynx).Resample = chkResampleHydrolynx.Checked
        cboResampleHydrolynx.Enabled = chkResampleHydrolynx.Checked
    End Sub

    Private Sub chkResampleAquarius_CheckedChanged(sender As Object, e As EventArgs) Handles chkResampleAquarius.CheckedChanged
        CType(lstImports(cboConnectionName.SelectedIndex), clsImportAquarius).Resample = chkResampleAquarius.Checked
        lblResampleAquarius.Enabled = chkResampleAquarius.Checked
        txtResampleAquarius.Enabled = chkResampleAquarius.Checked
    End Sub

    Private Sub chkDateRange_CheckedChanged(sender As Object, e As EventArgs) Handles chkDateRange.CheckedChanged
        lstImports(cboConnectionName.SelectedIndex).OverrideDateRange = chkDateRange.Checked
        dtFirstDate.Enabled = chkDateRange.Checked
        dtLastDate.Enabled = chkDateRange.Checked
        txtMinDays.Enabled = Not chkDateRange.Checked
        txtMaxDays.Enabled = Not chkDateRange.Checked
    End Sub

    Private Sub dtFirstDate_ValueChanged(sender As Object, e As EventArgs) Handles dtFirstDate.ValueChanged
        lstImports(cboConnectionName.SelectedIndex).FirstDate = dtFirstDate.Value
    End Sub

    Private Sub dtLastDate_ValueChanged(sender As Object, e As EventArgs) Handles dtLastDate.ValueChanged
        lstImports(cboConnectionName.SelectedIndex).LastDate = dtLastDate.Value
    End Sub

    Private Sub txtDatabase_Validating(sender As Object, e As CancelEventArgs) Handles txtDatabaseName.Validating
        CType(lstImports(cboConnectionName.SelectedIndex), clsImportSCADA).DatabaseName = txtDatabaseName.Text
    End Sub

    Private Sub txtFolder_Validating(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles txtFolder.Validating
        With CType(sender, TextBox)
            .Text = .Text.TrimEnd(New Char() {"\"})
            If My.Computer.FileSystem.DirectoryExists(.Text) Then
                CType(lstImports(cboConnectionName.SelectedIndex), clsImportFile).ImportFolder = .Text
            Else
                e.Cancel = True
            End If
        End With
    End Sub

    Private Sub txtFolderHydrolynx_Validating(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles txtFolderHydrolynx.Validating
        With CType(sender, TextBox)
            .Text = .Text.TrimEnd(New Char() {"\"})
            If My.Computer.FileSystem.DirectoryExists(.Text) Then
                CType(lstImports(cboConnectionName.SelectedIndex), clsImportHydrolynx).ImportFolder = .Text
            Else
                e.Cancel = True
            End If
        End With
    End Sub

    Private Sub txtHeader_Validating(sender As Object, e As CancelEventArgs) Handles txtHeader.Validating, txtMappingSCADA.Validating, txtMappingHydrolynx.Validating, txtMappingAquarius.Validating
        With CType(sender, TextBox)
            If My.Computer.FileSystem.FileExists(.Text) Then
                lstImports(cboConnectionName.SelectedIndex).MappingFile = .Text
            Else
                e.Cancel = True
            End If
        End With
    End Sub

    Private Sub cboTableSCADA_Validating(sender As Object, e As CancelEventArgs) Handles cboTableSCADA.Validating
        CType(lstImports(cboConnectionName.SelectedIndex), clsImportSCADA).SourceTable = cboTableSCADA.Text
    End Sub

    Private Sub txtPswdAquarius_Validating(sender As Object, e As CancelEventArgs) Handles txtPswdAquarius.Validating
        CType(lstImports(cboConnectionName.SelectedIndex), clsImportAquarius).Password = txtPswdAquarius.Text
    End Sub

    Private Sub txtPswdSCADA_Validating(sender As Object, e As CancelEventArgs) Handles txtPswdSCADA.Validating
        CType(lstImports(cboConnectionName.SelectedIndex), clsImportSCADA).Password = txtPswdSCADA.Text
    End Sub

    Private Sub txtServerAquarius_Validating(sender As Object, e As CancelEventArgs) Handles txtServerAquarius.Validating
        CType(lstImports(cboConnectionName.SelectedIndex), clsImportAquarius).ServerName = txtServerAquarius.Text
    End Sub

    Private Sub txtServerSCADA_Validating(sender As Object, e As CancelEventArgs) Handles txtServerSCADA.Validating
        CType(lstImports(cboConnectionName.SelectedIndex), clsImportSCADA).ServerName = txtServerSCADA.Text
    End Sub

    Private Sub txtTime_Validating(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles txtTime.Validating
        Dim times() As String = txtTime.Text.Split(New Char() {" ", ",", ";"}, StringSplitOptions.RemoveEmptyEntries)
        For Each t In times
            If Not IsDate(t) Then e.Cancel = True
        Next
    End Sub

    Private Sub txtTime_Validated(sender As Object, e As System.EventArgs) Handles txtTime.Validated
        'reformat list of times for consistency
        Dim times() As String = txtTime.Text.Split(New Char() {" ", ",", ";"}, StringSplitOptions.RemoveEmptyEntries)
        Dim s = ""
        For Each t In times
            s &= IIf(s = "", "", ", ") & CDate(t).ToString("HH:mm")
        Next
        txtTime.Text = s
    End Sub

    Private Sub txtDays_Validating(sender As Object, e As CancelEventArgs) Handles txtMinDays.Validating, txtMaxDays.Validating, txtResampleAquarius.Validating
        Dim s As String = CType(sender, TextBox).Text.Trim
        Dim minval As Integer
        If sender Is txtMinDays Then
            minval = 1
        ElseIf sender Is txtMaxDays Then
            minval = 0
        ElseIf sender Is txtResampleAquarius Then
            minval = 5
        End If
        If Not IsNumeric(s) OrElse Val(s) < minval Then e.Cancel = True
    End Sub

    Private Sub txtMinDays_Validated(sender As Object, e As EventArgs) Handles txtMinDays.Validated
        lstImports(cboConnectionName.SelectedIndex).MinDays = Val(txtMinDays.Text)
    End Sub

    Private Sub txtMaxDays_Validated(sender As Object, e As EventArgs) Handles txtMaxDays.Validated
        lstImports(cboConnectionName.SelectedIndex).MaxDays = Val(txtMaxDays.Text)
    End Sub

    Private Sub txtResample_Validated(sender As Object, e As EventArgs) Handles txtResampleAquarius.Validated
        CType(lstImports(cboConnectionName.SelectedIndex), clsImportAquarius).ResampleInterval = Val(txtResampleAquarius.Text)
    End Sub

    Private Sub txtUserNameAquarius_Validating(sender As Object, e As CancelEventArgs) Handles txtUserNameAquarius.Validating
        CType(lstImports(cboConnectionName.SelectedIndex), clsImportAquarius).UserName = txtUserNameAquarius.Text
    End Sub

    Private Sub txtUserNameSCADA_Validating(sender As Object, e As CancelEventArgs) Handles txtUserNameSCADA.Validating
        CType(lstImports(cboConnectionName.SelectedIndex), clsImportSCADA).UserName = txtUserNameSCADA.Text
    End Sub

    Private Sub btnOK_Run_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOK.Click, btnRun.Click
        SetKey(enumTaskKey.LastConnection, cboConnectionName.Text)
        SetKey(enumTaskKey.ImportActivated, chkActivate.Checked)
        SetKey(enumTaskKey.ImportTime, txtTime.Text)
        SetKey(enumTaskKey.NumConnections, cboConnectionName.Items.Count)
        For i As Integer = 0 To cboConnectionName.Items.Count - 1
            Dim SectionName As String = "Connection_" & i
            lstImports(i).Save(SectionName)
        Next
        Me.DialogResult = IIf(sender Is btnOK, System.Windows.Forms.DialogResult.OK, System.Windows.Forms.DialogResult.Yes)
        Me.Close()
    End Sub

    Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        Me.DialogResult = System.Windows.Forms.DialogResult.Cancel
        Me.Close()
    End Sub

    Private Sub cboTableSCADA_DropDownClosed(sender As Object, e As EventArgs) Handles cboTableSCADA.DropDownClosed
        With cboTableSCADA
            .AutoCompleteMode = AutoCompleteMode.SuggestAppend
            .AutoCompleteSource = AutoCompleteSource.ListItems
        End With
    End Sub

End Class
